//
//  UIButtonEx.swift
//
//  Created by wq on 2024/1/8.
//

import Foundation

public enum ButtonImageEdgeInsetsStyle:Int {
    ///image 上 label下
    case ButtonImageEdgeInsetsStyleTop = 0
    ///image左 label右
    case ButtonImageEdgeInsetsStyleLeft = 1
    ///image下 label上
    case ButtonImageEdgeInsetsStyleBottom = 2
    ///image右 label左
    case ButtonImageEdgeInsetsStyleRight = 3
}
public extension UIButton {
    
    func adjustsFontSize(minimumScaleFactor:CGFloat = 0.7) {
        self.titleLabel?.adjustsFontSize(minimumScaleFactor: minimumScaleFactor)
    }
    
    func edgeInsets(_ style: ButtonImageEdgeInsetsStyle, _ space: CGFloat)  {
        let imgWidth = self.imageView!.frame.width
        let imgHeight = self.imageView!.frame.height
        
        var labWidth: CGFloat = 0.0
        var labHeight: CGFloat = 0.0
        let version: Float = (UIDevice.current.systemVersion as NSString).floatValue
        if version >= 8.0 {
            labWidth = self.titleLabel!.intrinsicContentSize.width
            labHeight = self.titleLabel!.intrinsicContentSize.height
        } else {
            labWidth = self.titleLabel!.frame.width
            labHeight = self.titleLabel!.frame.height
        }
        
        var imageEdgeInsets: UIEdgeInsets = UIEdgeInsets.zero
        var labelEdgeInsets: UIEdgeInsets = UIEdgeInsets.zero
        
        switch style {
        case .ButtonImageEdgeInsetsStyleTop:
            imageEdgeInsets = UIEdgeInsets.init(top: -labHeight - space * 0.5, left: 0, bottom: 0, right: -labWidth)
            labelEdgeInsets = UIEdgeInsets.init(top: 0, left: -imgWidth, bottom: -imgHeight - space * 0.5, right: 0)
            break
        case .ButtonImageEdgeInsetsStyleLeft:
            
            imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -space * 0.5, bottom: 0, right: space * 0.5)
            labelEdgeInsets = UIEdgeInsets.init(top: 0, left: space * 0.5, bottom: 0, right: -space * 0.5)
            break
        case .ButtonImageEdgeInsetsStyleBottom:
            
            imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: -labHeight - space * 0.5, right: -labWidth)
            labelEdgeInsets = UIEdgeInsets.init(top: -imgHeight - space * 0.5, left: -imgWidth, bottom: 0, right: 0)
            break
        case .ButtonImageEdgeInsetsStyleRight:
            
            imageEdgeInsets = UIEdgeInsets.init(top: 0, left: labWidth + space * 0.5, bottom: 0, right: -labWidth - space * 0.5)
            labelEdgeInsets = UIEdgeInsets.init(top: 0, left: -imgWidth - space * 0.5, bottom: 0, right: imgWidth + space * 0.5)
            break
        }
        
        self.titleEdgeInsets = labelEdgeInsets
        self.imageEdgeInsets = imageEdgeInsets
    }
}
